package net.tv90.shoppingserver.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import net.tv90.shoppingserver.exception.ServerException;
import net.tv90.shoppingserver.model.dto.UserRegisterDTO;
import net.tv90.shoppingserver.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

@Validated
@CrossOrigin
@Controller
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping("/user/login")
    public String loginUser(String username, String password, Model model) {
        try {
            userService.login(username, password);
        } catch (ServerException e) {
            model.addAttribute("errMsg", e.getMessage());
            return "login";
        }
        model.addAttribute("username", username);
        return "redirect:/";
    }

    @PostMapping("/user/register")
    public String registerUser(UserRegisterDTO dto, Model model) {
        try {
            userService.register(dto);
        } catch (ServerException e) {
            model.addAttribute("errMsg", e.getMessage());
            return "register";
        }
        return "redirect:/login";
    }

    @GetMapping("/user/logout")
    @SaCheckLogin
    public String logoutUser() {
        try {
            userService.logout();
        } catch (ServerException e) {
            return "redirect:/";
        }
        return "redirect:/";
    }

}
